import 'package:app/services/address.dart';
import 'package:app/services/dio_manager.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:bruno/bruno.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:intl/intl.dart';
import '../../../common/colors.dart';
import '../leave_model.dart';
import '../leave_type_module/leave_type_view.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:get/route_manager.dart';

class CreateLeaveController extends GetxController{


  TextEditingController editingController = TextEditingController();


  String startTime = '请选择开始时间';
  String endTime = '结束时间';

  var displayStartTime;
  var displayEndTime;
  var disPlayDay;

  String holidayStatusName = '请选择请假类型';
  int? holidayStatusId;

  String requestUnitName = '';
  String? requestUnitId;


  List listFilePaths = [];
  String fileName = '';
  /// 选择请假类型
  void tapClickLeaveType()async{
    var data = await Get.to(LeaveTypeView());
    if(data!=null){
      print(data);
      holidayStatusName = data['name'];
      holidayStatusId = data['id'];
      if(data['requestUnit']=='day'){
        requestUnitName = '天';
        requestUnitId = 'day';
      }else if(data['requestUnit']=='hour'){
        requestUnitName = '小时';
        requestUnitId = 'hour';
      }else{
        requestUnitName = '半天';
        requestUnitId = 'half_day';
      }
    }
    update();
  }

  /// 点击附件icon
  tapClickAccessory(){
    // actions.clear();
    showModalBottomSheet(
        context: Get.overlayContext!,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return BrnCommonActionSheet(
            title: "",
            actions: actions,
            clickCallBack: (
                int index,
                BrnCommonActionSheetItem actionEle,
                )async {
              if (index == 0) {
                ImagePickers.openCamera(
                    cropConfig: CropConfig(
                        enableCrop: false,
                        width: 2,
                        height: 3))
                    .then((Media? media) {
                  // _listImagePaths.clear();
                  if (media != null) {

                    var fileParams = {
                      'name':'${media.path}',
                      'path':'${media.path}',
                    };
                    listFilePaths.clear();
                    fileName = '${media.path}';
                    listFilePaths.add(fileParams);

                    print(listFilePaths);
                  }
                  update();
                });
              }
              if (index == 1) {
                ImagePickers.openCamera(
                    cameraMimeType:
                    CameraMimeType.video)
                    .then((media) {
                  // listFilePaths.clear();
                  if (media != null) {
                    print(media.path);
                    var fileParams = {
                      'name':'${media.path}',
                      'path':'${media.path}',
                    };
                    listFilePaths.clear();
                    fileName = '${media.path}';
                    listFilePaths.add(fileParams);
                  }
                  update();
                });
              }
              if (index == 2) {
                try {
                  ImagePickers.pickerPaths(
                    galleryMode: GalleryMode.image,
                    showGif: false,
                    selectCount: 1,
                    showCamera: false,
                    cropConfig: CropConfig(enableCrop: true, height: 1, width: 1),
                    compressSize: 300,
                    uiConfig: UIConfig(
                      uiThemeColor: AppColor.themeColor,
                    ),
                  ).then((value) {
                    var fileParams = {
                      'name':'${value[0].path}',
                      'path':'${value[0].path}',
                    };
                    listFilePaths.clear();
                    fileName = '${value[0].path}';
                    listFilePaths.add(fileParams);
                    update();
                  });
                  if (listFilePaths.length > 0) {
                    listFilePaths.forEach((media) {
                      print(media.path.toString());
                    });
                  }
                  update();
                } on PlatformException {}
              }
              if(index == 3){
                //往下开始用filepick提供的方法
                FilePickerResult? result = await FilePicker.platform.pickFiles(
                  type: FileType.any,
                  // allowedExtensions: ['text'],    //筛选文件类型
                );
                //这就用完了，下面就赋值了
                if (result != null) {
                  // listFilePaths.clear();
                  PlatformFile file = result.files.first;
                  print(result.files.first.path);
                  var fileParams = {
                    'name':'${file.name}',
                    'path':'${file.path}',
                  };
                  listFilePaths.clear();
                  listFilePaths.add(fileParams);

                  // listFilePaths.add(file.path);
                  fileName = result.files.first.name;
                  update();
                } else {
                  // User canceled the picker
                }
              }
              // String title = actionEle.title;
              // BrnToast.show("title: $title, index: $index", context);
            },
          );
        });
    update();
  }

  /// 点击添加附件
  // tapClcikAccess()async{
  //   //往下开始用filepick提供的方法
  //   FilePickerResult? result = await FilePicker.platform.pickFiles(
  //     type: FileType.any,
  //     // allowedExtensions: ['text'],    //筛选文件类型
  //   );
  //   //这就用完了，下面就赋值了
  //   if (result != null) {
  //     // listFilePaths.clear();
  //     PlatformFile file = result.files.first;
  //     print(result.files.first.path);
  //     var fileParams = {
  //       'name':'${file.name}',
  //       'path':'${file.path}',
  //     };
  //
  //     listFilePaths.add(fileParams);
  //
  //     // listFilePaths.add(file.path);
  //     fileName = result.files.first.name;
  //     update();
  //   } else {
  //     // User canceled the picker
  //   }
  // }

  /// 选择开始时间（天）
  tapClickStartTime(){
    String format = 'yyyy-MM-dd';
    BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig(titleContent: "选择时间");
    BrnDateRangePicker.showDatePicker(Get.context!,
        isDismissible: false,
        minDateTime: DateTime(2020, 06, 01, 00, 00, 00),
        maxDateTime: DateTime(2039, 07, 24, 23, 59, 59),
        pickerMode: BrnDateTimeRangePickerMode.date,
        minuteDivider: 10,
        pickerTitleConfig: pickerTitleConfig,
        dateFormat: format,
        initialStartDateTime: DateTime.now(),
        initialEndDateTime: DateTime.now().add(new Duration(days: 1)),
        onConfirm: (startDateTime, endDateTime, startlist, endlist) {

                var timeFormat = DateFormat("yyyy-MM-dd");
                var timeStr = timeFormat.format(startDateTime);
                startTime = timeStr;
                var timeStr1 = timeFormat.format(endDateTime);
                endTime = timeStr1;
                update();
          // BrnToast.show(
          //     "onConfirm:  $startDateTime   $endDateTime     $startlist     $endlist", Get.overlayContext!);
        }, onClose: () {
          print("onClose");
        }, onCancel: () {
          print("onCancel");
        }, onChange: (startDateTime, endDateTime, startlist, endlist) {
        });
  }

  /// 选择开始时间（小时）
  tapClickStartTimeHour(){
    String format = 'HH时:mm分';
    const String MIN_DATETIME = '2021-01-01 00:00:00';
    const String MAX_DATETIME = '2021-12-31 23:59:59';
    BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig(titleContent: "选择时间范围");
    BrnDateRangePicker.showDatePicker(Get.overlayContext!,
        minDateTime: DateTime.parse(MIN_DATETIME),
        maxDateTime: DateTime.parse(MAX_DATETIME),
        pickerMode: BrnDateTimeRangePickerMode.time,
        minuteDivider: 10,
        pickerTitleConfig: pickerTitleConfig,
        dateFormat: format,
        ///  设置不限制开始时间必须≤结束时间
        ///  isLimitTimeRange: false,
        initialStartDateTime: DateTime.now(),
        initialEndDateTime: DateTime.now().add(new Duration(hours: 2)),
        onConfirm: (startDateTime, endDateTime, startlist, endlist) {

          var timeFormat = DateFormat("yyyy-MM-dd HH:mm");
          var timeStr = timeFormat.format(startDateTime);

          var timeFormat11 = DateFormat("HH:mm");
          var timeStr11 = timeFormat11.format(startDateTime);
          var timeStr22 = timeFormat11.format(endDateTime);
          var timeFormat33 = DateFormat("yyyy-MM-dd");
          var timeStr33 = timeFormat33.format(endDateTime);


          startTime = timeStr;
         displayStartTime = timeStr11;
         displayEndTime = timeStr22;
         disPlayDay = timeStr33;

          var timeStr1 = timeFormat.format(endDateTime);
          endTime = timeStr1;

          update();

          // BrnToast.show(
          //     "onConfirm:  $startDateTime   $endDateTime     $startlist     $endlist", Get.overlayContext!);
        }, onClose: () {
          print("onClose");
        }, onCancel: () {
          print("onCancel");
        }, onChange: (startDateTime, endDateTime, startlist, endlist) {

          // BrnToast.show(
          //     "onChange:  $startDateTime   $endDateTime     $startlist     $endlist", Get.overlayContext!);
        });
  }

  /// 计算时间间隔(天)
  timeInterval(var startDate,var endDate){
    // var startDate = new DateTime(2020, 12, 20);
    // var endDate = new DateTime.now();
    var days = endDate.difference(startDate).inDays;
    return days;
  }

  /// 计算时间间隔(小时)
  timeIntervalHour(var startDate,var endDate){
    // var startDate = new DateTime(2020, 12, 20);
    // var endDate = new DateTime.now();
    var hour = endDate.difference(startDate).inMinutes;
    print(hour);
    return hour;
  }




  /// 点击发布
  requestDataWithPublish()async{

    Map<String,dynamic> flMap = {};
    if(listFilePaths.isNotEmpty){
      MultipartFile multipartFile = MultipartFile.fromFileSync(
        '${listFilePaths[0]['path']}',
        filename: '${listFilePaths[0]['name']}',
      );
      flMap['file'] = multipartFile;
    }
    if(requestUnitName=='小时'){
      flMap['start_date'] = displayStartTime;
      flMap['end_date'] = displayEndTime;
      flMap['date'] = '${disPlayDay}';
    }else{
      flMap['start_date'] = startTime;
      flMap['end_date'] = endTime;
    }

    flMap['name'] = editingController.text;
    flMap['holiday_status_id'] = holidayStatusId;
    flMap['request_unit'] = requestUnitId;
    if(model!=null){
      if(model!.id!>0){
        flMap['leave_id'] = model!.id!;

      }
    }
    var formData = FormData.fromMap(flMap);

    // var params = {
    //   'name':editingController.text,
    //   'holiday_status_id':holidayStatusId,
    //   'request_unit':requestUnitId,
    //   'start_date':startTime,
    //   'end_date':endTime,
    //   // 'date':'',
    //   // 'am_pm':'',
    // };
    print('flMap====${flMap}');
    var json = await DioManager().kkRequest(Address.hrLeaveWrite,bodyParams: formData,isShowLoad: true);
    if(json['errmsg'] == 'ok'){
      Get.back(result: 'refresh');
    }
    BotToast.showText(text: json['message']);
  }

  List<BrnCommonActionSheetItem> actions = [];

  LeaveItemModel? model;
  String title = '创建请假';
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    model = Get.arguments;
    // print('create_leave_id === ${model!.id}');
    if(model!=null){
      if(model!.id! > 0){
        editingController.text = model!.name!;
        title = '修改请假';
      }else{
        title = '创建请假';
      }
    }



    actions.add(BrnCommonActionSheetItem(
      '拍照',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '录视频',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '相册',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '文件',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
  }

}